package it.carlom.stikkyheader.core;

import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.ScrollView;
import ohos.agp.components.StackLayout;
import ohos.app.Context;

public class StikkyHeaderScrollView extends StikkyHeader {

    private final ScrollView mScrollView;

    StikkyHeaderScrollView(final Context context, final ScrollView scrollView, final Component header, final int minHeightHeader, final HeaderAnimator headerAnimator) {
        super(context, header, minHeightHeader, headerAnimator);
        this.mScrollView = scrollView;
    }

    @Override
    protected Component getScrollingView() {
        return mScrollView;
    }

    protected void init() {
        super.init();
        setupOnScrollListener();
        //暂不支持，ClipToPadding
    }

    @Override
    protected void setHeightHeader(int heightHeader) {
        super.setHeightHeader(heightHeader);
        Component componentAt = mScrollView.getComponentAt(0);
        if (componentAt instanceof DirectionalLayout) {
            Component mFakeHeader = new Component(mContext);
            StackLayout.LayoutConfig layoutConfig = new StackLayout.LayoutConfig(StackLayout.LayoutConfig.MATCH_PARENT, heightHeader);
            mFakeHeader.setLayoutConfig(layoutConfig);
            ((DirectionalLayout) componentAt).addComponent(mFakeHeader, 0);
        }
    }

    private void setupOnScrollListener() {
        mScrollView.getComponentTreeObserver().addScrolledListener(() -> {
            onScroll(-mScrollView.getScrollValue(Component.AXIS_Y));
        });
        //init scroll listener when the view is ready
        StikkyHeaderUtils.executeOnGlobalLayout(mScrollView, () -> onScroll(-mScrollView.getScrollValue(Component.AXIS_Y)));
    }

}
